﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Frogism.Core;
namespace Frogism.Domain {
  public class TransactionManager : ManagerBase<Transaction,ITransaction>{

    private Frogism.Data.TransactionLoader _Loader;
    public override Frogism.Core.ILoader<Transaction,ITransaction> Loader {
      get {
        if(_Loader == null) {
          _Loader = new Frogism.Data.TransactionLoader();
        }
        return _Loader;
      }
    }
    private IOrderedEnumerable<ITransaction> GetAllDecending() {
      return this.GetAll().OrderByDescending(t => t.TransactionDate);
    }
    private Collection<ITransaction> GetByDates(DateTime start, DateTime end) {
      return GetAllDecending().Where(t => (t.TransactionDate >= start) && (t.TransactionDate <= end)).ToCollection<ITransaction>();
    }
    public Collection<ITransaction> GetWeek() {
      DateTime WeekStart = DateTime.Now.StartOfWeek();
      DateTime WeekEnd = DateTime.Now.EndOfWeek();
      return GetByDates(WeekStart, WeekEnd);
    }
    public Collection<ITransaction> GetWeek(int index) {
      DateTime WeekStart = DateTime.Now.StartOfWeek().AddDays(7*index);
      DateTime WeekEnd = WeekStart.EndOfWeek();
      return GetByDates(WeekStart, WeekEnd);
    }
    public Collection<ITransaction> GetNoCategories() {
      IEnumerable<ITransaction> trans = GetAll();
      return trans.Where(t => t.TransactionDate.Year >=2008 && t.Category.Id == 0 && (t.TransactionType.Value == DBConst.TransactionTypeBill
          || t.TransactionType.Value == DBConst.TransactionTypeExpense
          || t.TransactionType.Value == DBConst.TransactionTypeInterest)).ToCollection<ITransaction>();

    }

    public Collection<ITransaction> GetRecent() {
      DateTime start = DateTime.Now.StartOfMonth();
      DateTime end = DateTime.Now.EndOfMonth();
      return GetByDates(start, end);
    }
    public Collection<ITransaction> GetUnConfirmed() {

      return GetAllDecending().Where(t => !t.IsConfirmed).ToCollection<ITransaction>();
    }

    public void Save(ITransaction transaction) {
      ((Frogism.Data.TransactionLoader)Loader).Save(transaction);
    }
    public void Create(ITransaction transaction) {
      ((Frogism.Data.TransactionLoader)Loader).Create(transaction);
    }
    public void Delete(int id) {
      ((Frogism.Data.TransactionLoader)Loader).Delete(id);
    }

  }
}
